var baseService = {
    baseUrl:""
};
function getQueryString_(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
    var r = window.location.search.substr(1).match(reg);
    if (r!=null)
        return (r[2]);
    return null;
}
//JS操作cookies方法!
//写cookies
function setCookie(name,value)
{
    var Days = 300;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/";
}

function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}
function delCookie(name)
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null)
        document.cookie= name + "="+cval+";expires="+exp.toGMTString()+";path=/";
}
var userCode=getQueryString_("userCode");
if(userCode!=null&&userCode!=""){
    localStorage.setItem("userCode",userCode);
}
baseService.ajaxRequest = function (url, param, callback,async) {
    var params=JSON.stringify(param, function (k, v) {
        return typeof v === "number" ? v + "" : v;
    });
    console.info(baseService.baseUrl+url);
    console.info(params);
    if($.showLoading) $.showLoading();
    $.ajax({
        url: baseService.baseUrl+url,
        data: {
            datas:params
        },
        async:async==null?true:async,
        dataType: "json",
        type: "post",
        success: function (data) {
            if(data.errorMsg=="操作失败：null"){
                //目前较多的情况是登录信息失效，重新登录即可
                $.confirm("系统遇到异常，重新登录可能可以解决，是否重新登录？","操作失败",function () {
                    localStorage.clear();
                    window.top.location.href = "/login";
                },function () {
                    $.hideLoading();
                })
                return;
            }
            console.warn(url);
            console.info(JSON.stringify(data));
            if($.hideLoading)  $.hideLoading();
            // 还原按钮执行中样式
            callback(data);
        },
        error: function (response) {
            console.error(url);
            console.info(JSON.stringify(response));
            if($.hideLoading) $.hideLoading();
            // 还原按钮执行中样式
            baseService.showErrorMessage(response);
        }
    });
};


baseService.showErrorMessage = function (response) {
    var title=response.status;
    var text="<div>系统异常</div><a href=\"javascript:;\" class=\"weui-btn weui-btn_mini weui-btn_default\" onclick='$(this).next().show()'>查看详情</a><div style= 'display:none;max-height: 300px; overflow: auto; text-align: left;font-size: 10px;'>"+response.responseText+"</div>";
    $.alert(text,title, function () {
        //未登录异常
        if (response.status == "601") {
            console.log(window.location.href);
            console.log($("#content_frame", window.top.document.body).attr("src"));
            var returnUrl = encodeURIComponent(window.location.href);
            window.top.location.href = "/login?returnUrl=" + returnUrl;
        }
    });
    if (response.code == "601") {
        window.top.location.href = "/login";
    }
};



baseService.getServerConstNames=function(constType) {
    var array = [];
    $(serverConst[constType]).each(function (i, item) {
        if(item!=null&&item.name!="") array.push(item.name);
    })
    return array;
}
baseService.getServerConstCodeByName=function(constType,name) {
    var code="";
    $(serverConst[constType]).each(function (i, item) {
        if(item.name==name)
            code= item.code;
    })
    return code;
}
baseService.getServerConstObjByName=function(constType,name) {
    var code="";
    var result={};
    $(serverConst[constType]).each(function (i, item) {
        if(item.name==name)
            result= item;
    })
    return result;
}
baseService.getServerConstNameByCode=function(constType,code) {
    var name="未知";
    $(serverConst[constType]).each(function (i, item) {
        if(item.code==code)
            name=item.name;
    })
    return name;
}
baseService.myBack=function(){
    if (window.history.length == 1) {
        window.close();
    } else {
        history.back();
    }
}
//必须先压进去一个页面，否则无法监听到后退
pushHistory();
window.addEventListener('popstate', function (e) {
    if($(".weui-popup__container").is(':visible')){
        $(".close-popup").trigger("click");
        history.pushState(null, null, document.URL);
    }else{
        history.back();
    }
});
function pushHistory() {
    var state = {
        title: "title",
        url: "#"
    };
    window.history.pushState(state, "title", "#");
}